package com.example.content.activity

import android.graphics.Color
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.bumptech.glide.Glide
import com.example.content.*
import com.example.content.databinding.ActivityPhotoDetailBinding
import com.example.content.ext.convertUrl
import com.example.content.manager.GlobalMgr
import com.example.content.manager.ShareMgr
import com.example.content.repository.bean.FollowReq
import com.example.content.repository.bean.UserActionReq
import com.example.content.viewmodule.DetailViewModel
import com.example.content.viewmodule.login.TokenStore
import com.github.chrisbanes.photoview.PhotoView
import com.gyf.immersionbar.ImmersionBar
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder

class PhotoDetailActivity : BaseActivity<ActivityPhotoDetailBinding, DetailViewModel>(), View.OnClickListener {
    private var totalSize = 0
    private var currentIndex = 0
    private val photoList = mutableListOf<String>()

    private var productId = -1

    override fun initView() {
       ImmersionBar.with(this).statusBarDarkFont(false).init()
    }

    override fun initData() {
        intent.extras.let { bundle ->
            if (bundle != null) {
                productId = bundle.getInt(PRODUCT_ID, -1)
                currentIndex = bundle.getInt(RESOURCE_POI)
            }
        }
        viewModel.getProductInfoById(listOf(productId))
    }

    private fun viewPageInit() {
        dataBinding.viewPager.adapter = ImagePagerAdapter()
        dataBinding.viewPager.currentItem = currentIndex
        dataBinding.photoIndex.text = "${currentIndex + 1}/${totalSize}"
    }

    override fun initListener() {
        dataBinding.backIcon.setOnClickListener(this)
        dataBinding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                val current = (position % totalSize) + 1
                dataBinding.photoIndex.text = "${current}/${totalSize}"
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })

        viewModel.productInfoResult.observe(this, observer = { it ->
            for (product in it) {
                when (product.resource_type) {
                    1 -> {
                        //视频类型
                        dataBinding.viewPager.visibility = View.GONE
                        dataBinding.videoPlay.visibility = View.VISIBLE
                        val thumbImageView = ImageView(this)
                        Glide.with(this).load(product.cover?.convertUrl()).into(thumbImageView)
                        dataBinding.videoPlay.backButton.visibility = View.GONE
                        val options = GSYVideoOptionBuilder()
                        options.setIsTouchWiget(true)
                            .setRotateViewAuto(false)
                            .setLockLand(false)
                            .setAutoFullWithSize(false)
                            .setShowFullAnimation(false)
                            .setNeedLockFull(true)
                            .setUrl(product.resource_list[0].convertUrl())
                            .setThumbImageView(thumbImageView)
                            .setCacheWithPlay(false)
                            .build(dataBinding.videoPlay)
                        dataBinding.videoPlay.fullscreenButton.setOnClickListener {
                            dataBinding.videoPlay.startWindowFullscreen(
                                dataBinding.videoPlay.context,
                                true,
                                true
                            )
                        }
                    }
                    2 -> {
                        //图片类型
                        photoList.clear()
                        for (url in product.resource_list) {
                            photoList.add(url.convertUrl())
                        }
                        totalSize = photoList.size
                        viewPageInit()
                        dataBinding.photoDesc.text = product.description
                    }
                }
                val userInfo = product.user_info
                Glide.with(this@PhotoDetailActivity).load(userInfo.avatar.convertUrl())
                    .into(dataBinding.headIcon)
                dataBinding.nickName.text = userInfo.nickname
                dataBinding.readCount.text = product.view_num.toString()
                //收藏
                dataBinding.collectionCount.text = product.collect_num.toString()
                if (product.collect_related) {
                    dataBinding.collectionImg.setImageResource(R.drawable.ic_collected)
                } else {
                    dataBinding.collectionImg.setImageResource(R.drawable.ic_collection_white)
                }
                dataBinding.collectionContainer.setOnClickListener {
                    val userActionReq = UserActionReq(productId, COLLECTION, if (product.collect_related) UN_ACTION else DO_ACTION)
                    viewModel.userAction(userActionReq)
                }
                GlobalMgr.collect.observe(this, {pair ->
                    if (productId == pair.first) {
                        if (pair.second) {
                            product.collect_related = !product.collect_related
                            if (product.collect_related) {
                                product.collect_num += 1
                            } else {
                                if (product.collect_num > 0) {
                                    product.collect_num -= 1
                                } else {
                                    product.collect_num = 0
                                }
                            }
                            dataBinding.collectionCount.text = product.collect_num.toString()
                            if (product.collect_related) {
                                dataBinding.collectionImg.setImageResource(R.drawable.ic_collected)
                            } else {
                                dataBinding.collectionImg.setImageResource(R.drawable.ic_collection_white)
                            }
                        }
                    }
                })

//                打赏
                dataBinding.rewardCount.text = product.reward_num.toString()
                if (product.reward_related) {
                    dataBinding.rewardImg.setImageResource(R.drawable.ic_rewarded)
                }
                dataBinding.shareCount.text = product.reward_num.toString()
                if (userInfo.id != TokenStore.userId) {
                    if (userInfo.follow_related == FOLLOW_UN) {
                        followBtnChange(R.drawable.ic_follow, R.string.follow_me, R.color.white)
                    } else {
                        followBtnChange(
                            R.drawable.ic_alread_follow,
                            R.string.already_follow,
                            R.color.followTextColor
                        )
                    }
                    dataBinding.followMe.setOnClickListener {
                        val isFollow = (product.user_info.follow_related != 0)
                        val req = FollowReq(product.user_id, if (isFollow) UN_ACTION else DO_ACTION)
                        viewModel.follow(req)
                    }

                    GlobalMgr.follow.observe(this, {followResp ->
                        if (followResp.follow == product.user_id) {
                            product.user_info.follow_related = followResp.follow_related
                            if (followResp.follow_related == FOLLOW_UN) {
                                dataBinding.followMe.text = this.getString(R.string.follow)
                                dataBinding.followMe.setTextColor(Color.parseColor("#FF4C6A"))
                            } else {
                                dataBinding.followMe.text = this.getString(R.string.already_follow)
                                dataBinding.followMe.setTextColor(Color.parseColor("#999999"))
                            }
                        }
                    })
                } else {
                    dataBinding.followMe.visibility = View.GONE
                }

                dataBinding.shareContainer.setOnClickListener {
                    ShareMgr.openBottom()
                }
            }
        })
    }

    private fun followBtnChange(@DrawableRes resId: Int, @StringRes text: Int, @ColorRes color:Int) {
        dataBinding.followMe.background =ContextCompat.getDrawable(this, resId)
        dataBinding.followMe.text = getString(text)
        dataBinding.followMe.setTextColor(ContextCompat.getColor(this, color))
    }

    override fun getLayoutId() = R.layout.activity_photo_detail

    inner class ImagePagerAdapter : PagerAdapter() {
        override fun getCount() = photoList.size

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val photoView = PhotoView(container.context)
            Glide.with(this@PhotoDetailActivity).load(photoList[position % totalSize]).into(photoView)
            container.addView(photoView)
            return photoView
        }

        override fun isViewFromObject(view: View, `object`: Any) = view === `object`

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View?)
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.back_icon -> {
                finish()
            }
            R.id.follow_me -> {

            }
        }
    }
}